//
//  CYMessageViewController.m
//  CreditAddressBook
//
//  Created by Mosu&Cuu on 15/12/23.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "CYMessageViewController.h"
#import "CYUser.h"
#import "CYURL.h"
#import "CYHttpTool.h"
#import "CYLoginHttpTool.h"
#import "CYJsonInfo.h"
#import "MJExtension.h"
#import "CYMessageTVCell.h"
#import "CYMessageModel.h"
#import "CYCreditTool.h"
#import "CYTool.h"
#import "CYMessageDtVC.h"
#import "TOWebViewController.h"
#import "LEBarButtonItem.h"
#import "FDSlideBar.h"
#import "JPUSHService.h"
#import "MJRefresh.h"

@interface CYMessageViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *_messageTabelView ;//下面的tabbleview
    NSMutableArray *_dataArray;//数据源
    NSMutableArray *_dataArray1;
    FDSlideBar *_slideBar;
    NSUInteger _slideBarSelectIndex;
     NSString *_totalPage;
    
}
@property (nonatomic, strong)UILabel *messlab;
@property (nonatomic, strong)UIView *lineview;
@property(nonatomic, assign) NSInteger currentPage;

@end

@implementation CYMessageViewController

-(void)viewWillAppear:(BOOL)animated{
    
    [self setupNavigationView];
     // 马上进入刷新状态
//     [_messageTabelView.mj_header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [JPUSHService setBadge:0];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    self.title = @"我的公告";
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _slideBar=[[FDSlideBar alloc]initWithFrame:CGRectMake(30, 64, self.view.width-60, 40)];
    [self.view addSubview:_slideBar];
    _lineview = [[UIView alloc]initWithFrame:CGRectMake(0, _slideBar.y+_slideBar.height, self.view.width, 1)];
    _lineview.backgroundColor = CYColor(100, 200, 100, 1);
    [self.view addSubview:_lineview];
    _slideBar.itemsTitle = @[@"公告",@"我的消息"];
    _slideBar.itemColor= [UIColor grayColor];
    _slideBar.sliderColor = CYColor(100, 200, 100,1);
    _slideBar.itemSelectedColor =  CYColor(100, 200, 100, 1);
    _slideBarSelectIndex = 0;
    [_slideBar slideBarItemSelectedCallback:^(NSUInteger idx) {
        _slideBarSelectIndex = idx;
         [_messageTabelView.mj_header beginRefreshing];
         [_messageTabelView reloadData];
    }];
    
    _dataArray = [NSMutableArray array];
    _dataArray1 = [NSMutableArray array];
     _totalPage = @"0";
//    LEBarButtonItem *itema = [[LEBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_overflowmenu"] andSelImage:nil andTitle:@"个人消息" target:self action:@selector(moreBtn)];
//
//    self.navigationItem.rightBarButtonItem = itema;
    
    [self downloaddata];
    [self cretetb];
    // Do any additional setup after loading the view.
}
-(void)endRefresh{
     [_messageTabelView.mj_header endRefreshing];
     [_messageTabelView.mj_footer endRefreshing];
}

- (void)setupNavigationView {
    
    UIView *naviView = [[UIView alloc] init];
    naviView.backgroundColor = CYNaviThemeColor;
    naviView.frame = CGRectMake(0, 0, self.view.width, 64);
    [self.view addSubview:naviView];
     // 添加下拉刷新和上拉加载更多
     __weak typeof(self) weakSelf = self;
     _messageTabelView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
          [_dataArray removeAllObjects];
          weakSelf.currentPage = 0;
          [weakSelf downloaddata];
     }];
     
     _messageTabelView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
          weakSelf.currentPage ++;
          //判断页数
          if (weakSelf.currentPage > [_totalPage integerValue]) {
               [_messageTabelView.mj_footer endRefreshingWithNoMoreData];
          }else {
               [weakSelf downloaddata];
          }
     }];
}


-(void)downloaddata{
     
     NSString *pageStr = [NSString stringWithFormat:@"%ld",(long)self.currentPage];
    CYUser *user = [CYLoginHttpTool userData].user;
//    [CYURL shared].getPushListByIos
    [CYHttpTool postWithURL:[CYURL shared].getPushListByIos  params:@{@"page":pageStr} success:^(id json) {
         [self endRefresh];
        //NSLog(@"message = %@",json);
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            NSDictionary *data = jsonInfo.data;
            NSArray *arr = [data valueForKey:@"pageItems"];
             _totalPage = [data valueForKey:@"totalNumber"];
            if (arr) {
                for (NSDictionary *dic in arr) {
                CYMessageModel *temp = [[CYMessageModel alloc]initWithDictionary:dic];
                    [_dataArray addObject:temp];
            }
        }
            
    }
    [_messageTabelView reloadData];
    } failure:^(NSError *error) {
         [self endRefresh];
    }];
    //个人消息
     
    [CYHttpTool postWithURL:[CYURL shared].getPushListByUserId params:@{@"userId":user.userId,@"token":user.token, @"page":pageStr} success:^(id json) {
       // NSLog(@"personmes = %@",json);
         [self endRefresh];
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            NSDictionary *data = jsonInfo.data;
            NSArray *arr = [data valueForKey:@"pageItems"];
             _totalPage = [data valueForKey:@"totalNumber"];
            if (arr) {
                for (NSDictionary *dic in arr) {
                    CYMessageModel *temp = [[CYMessageModel alloc]initWithDictionary:dic];
                    [_dataArray1 addObject:temp];
                }
            }
        }
         
        [_messageTabelView reloadData];
    } failure:^(NSError *error) {
         [self endRefresh];
         
    }];
}

-(void)cretetb{
    //[[ UIScreen mainScreen ] bounds].size.width
    _messageTabelView = [[UITableView alloc]initWithFrame:CGRectMake(0,_slideBar.height+_slideBar.y+10, self.view.width, [[UIScreen mainScreen]bounds].size.height-_slideBar.height-64) style:UITableViewStylePlain];
    _messageTabelView.backgroundColor = [UIColor whiteColor];
    _messageTabelView.dataSource = self;
    _messageTabelView.delegate = self;
    [_messageTabelView registerNib:[UINib nibWithNibName:@"CYMessageTVCell" bundle:nil] forCellReuseIdentifier:@"CYMessageTVCell"];
    [CYTool setExtraCellLineHiddenWithTableView:_messageTabelView];
    [self.view addSubview:_messageTabelView];
}

#pragma mark - tableview代理
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CYMessageTVCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYMessageTVCell" forIndexPath:indexPath];
    //cell.model = _dataArray[indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
     if (indexPath.row <= _dataArray.count) {
          if (_slideBarSelectIndex == 0) {
        cell.model = _dataArray[indexPath.row];
          }
    }else if(_slideBarSelectIndex == 1){
        cell.model = _dataArray1[indexPath.row];
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_slideBarSelectIndex == 0) {
    CYMessageDtVC *messagedt = [[CYMessageDtVC alloc]init];
    messagedt.cymessagemodel = [_dataArray objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:messagedt animated:YES];
    }
    else if(_slideBarSelectIndex == 1){
        CYMessageDtVC *messagedt = [[CYMessageDtVC alloc]init];
        messagedt.cymessagemodel = [_dataArray1 objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:messagedt animated:YES];
    }
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_slideBarSelectIndex ==0) {
        return _dataArray.count;
    }
    return _dataArray1.count;
}
#pragma mark -
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self= [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
